package com.epfresh.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.tablayout.utils.UnreadMsgUtils;
import com.epfresh.bean.OftenListCategoryBean;
import com.epfresh.fragment.OftenListGoodsFrag;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.DataManager;
import com.epfresh.views.MultiStateView;
import com.google.gson.Gson;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class OftenListActivity extends BaseActivity implements DataManager.OnCartCountChangeListener {
    private MultiStateView msv_view;
    private TabLayout often_tab_layout;
    private ViewPager vp_often;
    private MyFragmentPagerAdapter pagerAdapter;
    private OftenListCategoryBean oftenListCategoryBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_often_list);

        initView();
        DataManager.getInstance().registerMsgView("OftenListActivity", this);
        DataManager.getInstance().updateCartCnt();
        reqOftenCategory();
    }

    private void initView() {
        toolbarTitle.setText("常购清单");
        v_line.setVisibility(View.GONE);
        righticon.setVisibility(View.VISIBLE);
        righticon.setImageResource(R.mipmap.icon_often_cart);
        righticon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OftenListActivity.this,CartActivity.class);
                startActivity(intent);
            }
        });

        msv_view = findViewById(R.id.msv_view);
        msv_view.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        msv_view.setViewForState(R.layout.empty_often_list, MultiStateView.VIEW_STATE_EMPTY);
        msv_view.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);
        often_tab_layout = findViewById(R.id.often_tab_layout);
        vp_often = findViewById(R.id.vp_often);
        pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        vp_often.setAdapter(pagerAdapter);

        often_tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                vp_often.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        vp_often.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                often_tab_layout.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    /**
     * 请求获取常购清单tab数据
     */
    private void reqOftenCategory() {
        RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(AppPurchaseRouterConstant.cmd_store_offen_oftenList);
        requestEntity.putParameter("topCategoryId", "");
        requestEntity.putParameter("pageNumber", 0);
        requestEntity.putParameter("pageSize", "10");
        requestEntity.setCityId(ApplicationHelper.getInstance().getCity().getCityId());

        request(requestEntity, AppPurchaseRouterConstant.cmd_store_offen_oftenList, new OnRequestListener<OftenListCategoryBean>() {
            @Override
            public OftenListCategoryBean jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, OftenListCategoryBean.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
                msv_view.setViewState(MultiStateView.VIEW_STATE_ERROR);
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
                msv_view.setViewState(MultiStateView.VIEW_STATE_ERROR);
            }

            @Override
            public void onStart(Object tag) {
                msv_view.setViewState(MultiStateView.VIEW_STATE_LOADING);
            }

            @Override
            public void onResponse(ResponseEntity<OftenListCategoryBean> response, Object tag) {
                hideProgressDialog();
                if (response.getResponseElement() != null) {
                    if (response.getResponseElement().getTopCategory() != null && response.getResponseElement().getTopCategory().size() > 0) {
                        oftenListCategoryBean = response.getResponseElement();
                        msv_view.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        addTabs(getTabTitles(response.getResponseElement()));
                        setIndicatorWidth(often_tab_layout);
                        vp_often.setOffscreenPageLimit(response.getResponseElement().getTopCategory().size() - 1);
                        pagerAdapter.setDataInfo(getFragmentList(response.getResponseElement()));
                        pagerAdapter.notifyDataSetChanged();
                    } else {
                        msv_view.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                    }
                }

            }
        });
    }

    private void addTabs(List<String> tabTitles) {
        for (String tabTitle : tabTitles) {
            often_tab_layout.addTab(often_tab_layout.newTab().setText(tabTitle));
        }
    }

    /**
     * 得到所对应的tabTitles
     *
     * @param oftenListCategoryBean
     * @return
     */
    private List<String> getTabTitles(OftenListCategoryBean oftenListCategoryBean) {
        List<String> tabTitles = new ArrayList<>();
        for (OftenListCategoryBean.TopCategoryBean topCategoryBean : oftenListCategoryBean.getTopCategory()) {
            tabTitles.add(topCategoryBean.getName());
        }
        return tabTitles;
    }

    /**
     * 设置tab指示器的长度(随tab的长度)
     *
     * @param tabLayout
     */
    private void setIndicatorWidth(final TabLayout tabLayout) {
        tabLayout.post(new Runnable() {

            @Override
            public void run() {
                try {
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);
                    int dpMargin = LocalDisplay.dp2px(10);
                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);
                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        mTextView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                        tabView.setPadding(0, 0, 0, 0);
                        int width;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dpMargin;
                        params.rightMargin = dpMargin;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 得到fragmentList
     *
     * @param oftenListCategoryBean
     * @return
     */
    private List<BaseFragment> getFragmentList(OftenListCategoryBean oftenListCategoryBean) {
        List<BaseFragment> fragmentList = new ArrayList<>();
        int pos = -1;
        for (OftenListCategoryBean.TopCategoryBean topCategoryBean : oftenListCategoryBean.getTopCategory()) {
            pos += 1;
            OftenListGoodsFrag oftenListGoodsFrag = new OftenListGoodsFrag();
            Bundle bundle = new Bundle();
            bundle.putString("categoryId", topCategoryBean.getId());
            bundle.putInt("tabPos", pos);
            oftenListGoodsFrag.setArguments(bundle);
            fragmentList.add(oftenListGoodsFrag);
        }
        if (fragmentList.get(0) != null) {
            ((OftenListGoodsFrag) fragmentList.get(0)).setFirstInit(true);
        }

        return fragmentList;
    }

    @Override
    public void onCartCountChange(int count) {
        msg.setVisibility(View.VISIBLE);
        UnreadMsgUtils.show(msg, count);
    }

    static class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
        private List<BaseFragment> fragmentList;


        MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
            fragmentList = new ArrayList<>();
        }

        private void setDataInfo(List<BaseFragment> fragmentList) {
            this.fragmentList.clear();
            this.fragmentList.addAll(fragmentList);
        }


        @Override
        public Fragment getItem(int position) {
            return fragmentList == null ? null : fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList == null ? 0 : fragmentList.size();
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }

    /**
     * 动态删除tab所对应的列表
     *
     * @param tabPos
     */
    public void removeOftenTab(int tabPos) {
        List<OftenListCategoryBean.TopCategoryBean> topCategory = oftenListCategoryBean.getTopCategory();
        topCategory.remove(tabPos);
        often_tab_layout.removeTabAt(tabPos);
        if (topCategory.size() == 0) {
            msv_view.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        } else {
            pagerAdapter.setDataInfo(getFragmentList(oftenListCategoryBean));
            pagerAdapter.notifyDataSetChanged();
        }
    }

    public View getShoppingCartView() {
        return righticon;
    }
}
